#!/bin/sh
. /etc/profile
IFS="
"
cd $(dirname $0)
export MYNAME=$(cd ..; basename $(pwd))

cd /home/$MYNAME || exit 1
BASEDIR=$(/bin/pwd)
cd Files || exit 1
FILESDIR=$(/bin/pwd)

mkdir -p $FILESDIR/etc
touch $FILESDIR/etc/mtab

echo "Starting proc.sh for '$MYNAME'."
unset SUB


status()
{
	CODE=$1
	shift
	MESSAGE="$@"
	echo "[$CODE] $MESSAGE"
	uni set /tmp/addons/$MYNAME/status "$CODE"
	uni set /tmp/addons/$MYNAME/status\ message "$MESSAGE"
}

unmount_all()
{
	# This might look like a bit of overkill, but it's important
	# because Weaver (as of 4.3.2d) happily traverses into mounted
	# filesystems when it goes to delete a team's files.  If we don't
	# successfully unmount all our filesystems and someone goes to
	# delete the team, it could end up wiping out the entire
	# filesystem!
	#
	# We supply our own umount in the chroot because weaver's one
	# doesn't have the -l (lazy unmount) option, which allows us to
	# unmount even if the filesystem is still in use for some reason.
	# That option gives us lots of extra safety.
	#
	# The "sort -r" is to unmount inner filesystems before outer ones.
	# Because /proc files act oddly, we also make sure to read all of
	# /proc/mounts before we actually mount/unmount anything, which
	# would change the "contents" of the file.
	status 1 "Checking mounts..."
	OIFS="$IFS"
	IFS=" "
	cat /proc/mounts \
	 | while read dev dir junk; do
		echo "$dir"
	done \
	 | sort -r \
	 | grep -e "^$FILESDIR" \
	 | sed "s,^$FILESDIR/,," \
	 | while read dir; do
		status 1 "Unmounting: $dir in $FILESDIR"
		chroot $FILESDIR umount -n $dir || (
			status 1 "Unmounting: $dir (LAZY!)"
			chroot $FILESDIR umount -n -l $dir
		)
	done
	IFS="$OIFS"
}

stopit()
{
	trap - TERM QUIT INT
	if [ -n "$SUB" ]; then
		status 1 "Waiting for subproc (#$SUB)..."
		kill $SUB
		wait $SUB
	fi
	status 1 "Stopping (1)..."
	unmount_all
	status 1 "Stopping (2)..."
	exit
}

trap stopit TERM QUIT INT
	
unmount_all

mkdir -p dev
rm -f dev/null
mknod dev/null c 1 3

status 1 "Mounting sub-filesystems..."
mkdir -p tmp filesystem/VERSA
mount -t tmpfs none tmp || stopit
mount -t tmpfs none filesystem/VERSA || stopit
mkdir filesystem/VERSA/.home filesystem/VERSA/.tmp || stopit
ln -s ../filesystem/VERSA/.tmp/rcmd tmp/
ln -s ../filesystem/VERSA/.tmp/uniconfd tmp/
ln -s .tmp/uniconfd filesystem/VERSA/uniconfd
hostname >filesystem/VERSA/hostname
hostname >filesystem/VERSA/mailname
cp /etc/resolv.conf filesystem/VERSA/resolv.conf
mount -o bind /home/. filesystem/VERSA/.home || stopit
mount -o bind /tmp/. filesystem/VERSA/.tmp || stopit

OK=1
if [ -x filesystem/proc.sh ]; then
	status 1 "Starting subproc..."
	
	# for legacy procedures that don't reset the status message
	uni del /tmp/addons/$MYNAME/status\ message
	
	filesystem/proc.sh &
	SUB=$!
	wait || unset OK
fi

COUNT=0
while true; do
	if [ -n "$OK" ]; then
		# status 2 "Idle. ($COUNT)"
		status 2 "Idle."
		COUNT=$(($COUNT+1))
	fi
	sleep 10
done

status 0 Stopped.
exit 0
